//index.js
//获取应用实例
var App = getApp()
Page({
  data: {
    cccc:"",
    ks:"",
    js:"",
    motto: 'Hello World',
    merchants: {},
    prompt: {
      hidden: !0,
    },
    dates: [],
    defaultDate: '',
    defaultTime: '',
    defaultWeek: '',
    productStatus: 0
  },
  onLoad(option) {

    console.log(option)

    let agent = wx.getStorageSync('agent');
    let position = wx.getStorageSync('position');
    let userId = wx.getStorageSync("userId");
    let products = wx.getStorageSync("products");
    this.setData({
      // qian: products[0].price,
      qian:1,
      chaxing: wx.getStorageSync('defaultCar').carInfo,
      s_id: option.s_id,
      canshu: JSON.parse(option.can)
    })
    // debugger
    if (option.year) {

      let defaultDate = option.year + '-' + option.month + '-' + option.day;
      let selectDate = new Date(defaultDate);

      let arr = [];
      for (let i = 0; i < 5; i++) {
        let today = new Date();
        let date = new Date(option.year + '-' + option.month + '-' + option.day)
        let obj = {};
        let a = date.setDate(date.getDate() + i);
        let b = new Date(a);
        let year = b.getFullYear();
        let month = b.getMonth() + 1;
        let day = b.getDate();
        let week = b.getDay();
        obj.date = month + '-' + day;
        obj.fullDate = year + '-' + month + '-' + day;

        switch (week) {
          case 0:
            obj.week = "周日";
            break;
          case 1:
            obj.week = "周一";
            break;
          case 2:
            obj.week = "周二";
            break;
          case 3:
            obj.week = "周三";
            break;
          case 4:
            obj.week = "周四";
            break;
          case 5:
            obj.week = "周五";
            break;
          case 6:
            obj.week = "周六";
            break;
          default:
            break;
        }

        if (today.getTime() == b.getTime() && i == 0) {
          obj.week = "今天";
        }
        if (today.getTime() != b.getTime() && i == 0) {
          obj.className = "active";
          this.setData({
            defaultWeek: obj.week
          });
        } else {
          obj.className = '';
        }
        arr.push(obj);
        this.setData({
          dates: arr,
          defaultDate
        });
      }
    } else {
      
      let today = new Date();
      // 修改位置 +1
      let nextDay = today.setDate(today.getDate());
      let year = new Date(nextDay).getFullYear();
      let month = new Date(nextDay).getMonth() + 1;
      let day = new Date(nextDay).getDate();
      let defaultDate = year + '-' + month + '-' + day;

      let arr = [];
      for (let i = 0; i < 5; i++) {
        let date = new Date();
        let obj = {};
        let a = date.setDate(date.getDate() + i);
        let b = new Date(a);
        let year = b.getFullYear();
        let month = b.getMonth() + 1;
        let day = b.getDate();
        let week = b.getDay();
        obj.date = month + '-' + day;
        obj.fullDate = year + '-' + month + '-' + day;

        switch (week) {
          case 0:
            obj.week = "周日";
            break;
          case 1:
            obj.week = "周一";
            break;
          case 2:
            obj.week = "周二";
            break;
          case 3:
            obj.week = "周三";
            break;
          case 4:
            obj.week = "周四";
            break;
          case 5:
            obj.week = "周五";
            break;
          case 6:
            obj.week = "周六";
            break;
          default:
            break;
        }
        if (date.getTime() == b.getTime() && i == 0) {
          obj.week = "今天";
        }
        if (i == 0) {
          // 修改位置
          obj.className = "active";
          this.setData({
            defaultWeek: obj.week
          });
        } else {
          obj.className = '';
        }
        arr.push(obj);
      }
      this.setData({
        dates: arr,
        defaultDate
      });
    }

    this.setData({
      agent,
      position,
      userId,
      // productStatus: option.productStatus,
      productStatus:0

    });

    this.onPullDownRefresh();
  },
gouxu:function(){
  wx.showToast({
    title: '不可预约',
    image: '../../../assets/images/warning.png',
    duration: 1000
  })
},
  initData() {
    const merchants = {
      items: [],
      total: '',
      params: {
        page: 1,
        pageCount: 10
      }
    }
    this.setData({
      merchants: merchants
    })
 
  },
  
  getList(cb) {
    let {
      merchants,
      agent,
      position
    } = this.data;
    let params = merchants.params;
    let location = position.location;
    params.sellerId = agent.id;
    params.userId = this.data.userId;
    params.lng = location.split(',')[0];
    params.lat = location.split(',')[1];
 params.dataTime = this.data.defaultDate
    params.buyerCouponsId = this.data.s_id

    App.HttpService.getMerchantss(params).then(res => {
      cb && cb()
      let data = res.data.data
      //...es6用法 数组扩展用法
     var sss= params.page
     if(sss>1){
       merchants.items = [...merchants.items,...data.shopList]
     }else{
       merchants.items = [...data.shopList]

     }
    //  debugger

      if (data.shopList.length > 0) {
        params.page = params.page + 1
        merchants.total = data.counts
      }
      this.setData({
        merchants
      })
    },
     e => {
      cb && cb()
    })
  },

  onPullDownRefresh() {
    wx.showNavigationBarLoading()
    this.initData()
    this.getList(() => {
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
    })
  },
  onReachBottom() {
    let merchants = this.data.merchants
    if (merchants.items.length === merchants.total) {
      return
    }
    this.getList()
  },
  toMerchant(e) {
    // let {id, name} = e.currentTarget.dataset
    // wx.navigateTo({
    //  url: `/pages/merchants/detail/detail?merchantId=${id}&merchantName=${name}`
    // })
  },
  booking(e) {
    let {
      id,
      name,
      phone,
      address
    } = e.currentTarget.dataset

    let {
      productStatus
    } = this.data
    if (productStatus == 0) { // 普通商品选择店铺
      this.data.productStatus = productStatus;
      wx.navigateTo({
        url: `/pages/order/confirm/index?merchantId=${id}&merchantName=${name}&phone=${phone}&address=${address}`
      })
 
    } else if (productStatus == 1) { // 拼团商品选择店铺
      this.data.productStatus = productStatus;
      wx.navigateTo({
        url: `/pages/group-buying/confirm/index?merchantId=${id}&merchantName=${name}`
      })

    } else if (productStatus == 2) { // 套餐商品选择店铺
      this.data.productStatus = productStatus;
      wx.navigateTo({
        url: `/pages/order/confirm/index?merchantId=${id}&merchantName=${name}`
      })


    }
  },
  // 跳转到日历
  toCalendar() {
    wx.navigateTo({
      url: `/pages/merchants/calendar/index?date=${this.data.defaultDate}&productStatus=` + this.data.productStatus,
    })
  },
  //  选择日期
  chooseDate(e) {
    let index = e.currentTarget.dataset.index;
    let date = e.currentTarget.dataset.date;
    let week = e.currentTarget.dataset.week;
    for (let i = 0; i < 5; i++) {
      let className = "dates[" + i + "].className";
      this.setData({
        [className]: ""
      });
    }
    if (e.currentTarget.dataset.week == "今天") {
      // index += 1;
      // 修改位置
      let className = "dates[" + index + "].className";
      this.setData({
        [className]: 'active',
        defaultDate: date
      });
      return;
    }
    let className = "dates[" + index + "].className";
    this.setData({
      [className]: 'active',
      defaultDate: date,
      defaultWeek: week 
    });

    var merchants = this.data.merchants;
    merchants.params.page = 1;
    this.setData({
      merchants: merchants
    })
// debugger
    this.getList();
  },
  // 选择时间
  bindTimeChange(e) {
    this.setData({
      defaultTime: e.detail.value
    });
 
  
    let {
      id,
      name,
      address,
      phone,
      distance
    } = e.currentTarget.dataset

    let {
      productStatus
    } = this.data
    let date = this.data.defaultDate;
    let week = this.data.defaultWeek;
    let time = this.data.defaultTime;
    let s_id =this.data.s_id
    console.log(productStatus,"----")
   
    if (productStatus == 0) { // 普通商品选择店铺
    // debugger
    var can =JSON.stringify(this.data.canshu)
      wx.navigateTo({
        url: `/pages/order/confirms/index?merchantId=${id}&merchantName=${name}&date=${date}&week=${week}&time=${time}&address=${address}&phone=${phone}&distance=${distance}&s_id=${s_id}&canshu=${can}`
      })
     
    } else if (productStatus == 1) { // 拼团商品选择店铺
      // debugger

      wx.navigateTo({
        url: `/pages/group-buying/confirm/index?merchantId=${id}&merchantName=${name}&date=${date}&week=${week}&time=${time}&address=${address}&phone=${phone}&distance=${distance}`
      })
    } else if (productStatus == 2) { // 套餐商品选择店铺
      // debugger

      wx.navigateTo({
        url: `/pages/order/confirm/index?merchantId=${id}&merchantName=${name}&date=${date}&week=${week}&time=${time}&address=${address}&phone=${phone}&distance=${distance}`
      })
    }
  },
  // 获取到当前门店的时间段
  // yudings: function(e) {
  //   console.log(66, e.currentTarget.dataset)
  //   let sindex = e.currentTarget.dataset.idx
  //   let s_id = e.currentTarget.dataset.sid
  //   let time = this.data.defaultDate
  //   debugger
  //   App.HttpService.yy({
  //     shopId: s_id,
  //     dataTime: time
  //   }).then(res => {
  //     console.log(666, res)
  //     var k = res.data.data
  //     var add = []
  //     k.forEach(v => {
  //       console.log(v);
  //       var p = v.startTime.substring(v, 5)
  //       var n = v.endTime.substring(v, 5)
  //       add.push(p + ' - ' + n)
  //     });
  //     this.setData({
  //       shij: add
  //     })
  //   })
  // },
  bodadianhua: function(e) {
    console.log(e.currentTarget.dataset.s)
    let dh = e.currentTarget.dataset.s
    wx.makePhoneCall({
      phoneNumber: dh,
    })
  },

  onShow(e) {
    console.log(e)
    if (this.data.cccc) {

      let defaultDate = this.data.cccc

      var selectDate = new Date((defaultDate.replace(/-/g, "/")));
      let arr = [];
      for (let i = 0; i < 5; i++) {
        let today = new Date();

        let date = selectDate
        console.log("dateda666666666te", date)

        let obj = {};
        let a = date.setDate(date.getDate() + i);
        let b = new Date(a);
        let year = b.getFullYear();
        let month = b.getMonth() + 1;
        let day = b.getDate();
        let week = b.getDay();
        obj.date = month + '-' + day;
        obj.fullDate = year + '-' + month + '-' + day;

        switch (week) {
          case 0:
            obj.week = "周日";
            break;
          case 1:
            obj.week = "周一";
            break;
          case 2:
            obj.week = "周二";
            break;
          case 3:
            obj.week = "周三";
            break;
          case 4:
            obj.week = "周四";
            break;
          case 5:
            obj.week = "周五";
            break;
          case 6:
            obj.week = "周六";
            break;
          default:
            break;
        }
        console.log("66666arr", arr)
        if (today.getTime() == b.getTime() && i == 0) {
          obj.week = "今天";
        }
        if (today.getTime() != b.getTime() && i == 0) {
          obj.className = "active";
          this.setData({
            defaultWeek: obj.week
          });
          console.log("目标错误位置", "obj", obj)

        } else {
          obj.className = '';
        }

        arr.push(obj);

        this.setData({
          dates: arr,
          defaultDate
        });

      }

    }


  }




})